package com.boot.until;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.jooq.Record;
import org.jooq.Result;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

//import okhttp3.OkHttpClient;

/**
 * Created by angrycans on 16/8/3.
 */
public class UtilBase {
    private static class TrustAllManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)

                throws CertificateException {
        }


        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("\\-", "");
    }


    public static String getJsonAsString(JsonObject json, String name) {
        String ret = json.get(name) == null ? null : json.get(name).getAsString();
        return ret;
    }

    public static double getJsonAsDouble(JsonObject json, String name) {
        double ret = json.get(name) == null ? 0.00d : json.get(name).getAsDouble();
        return ret;
    }

    public static int getJsonAsInt(JsonObject json, String name) {
        return json.get(name) == null ? -1 : json.get(name).getAsInt();
    }

    public static byte getJsonAsByte(JsonObject json, String name) {
        return json.get(name) == null ? -1 : json.get(name).getAsByte();
    }


    public static String createOrderNo() {
        Calendar ca = Calendar.getInstance();
        long seconds = System.currentTimeMillis() / 1000;
        String second_str = String.valueOf(seconds);
        String year_code[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
        return year_code[(int) Math.floor(ca.get(Calendar.YEAR)) - 2010] +
                Integer.toHexString(ca.get(Calendar.MONTH)).toUpperCase() + ca.get(Calendar.DATE) +
                second_str.substring(second_str.length() - 5, second_str.length()) + String.valueOf(System.currentTimeMillis()).substring(2, 5) + String.format("%02d", (int) (Math.random() * 100));

    }

    public static long getCurrentTime()
    {
        return System.currentTimeMillis() / 1000;
    }

    public static String getCurrentTimestamp()
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       return format.format(getCurrentTime());
    }

    public static String getIpAddr(HttpServletRequest req) {

        String ip = req.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getRemoteAddr();
        }

        return ip;

    }

    //将查询数据转换为jsonArray
    public static JsonArray dataChangeJsonArray(Result<Record> record) {
        try {
            // 元数据的数量
            int count = record.fieldsRow().size();
            String[] colNames = new String[count];
            String field = "";
            for(int i = 0; i < count; i++){
                // 字段名称
                field = record.field(i).toString();
                if (field.contains(".")) {
                    colNames[i] = field.substring(field.lastIndexOf(".") + 1,field.length());
                }
                else {
                    colNames[i] = field;
                }
            }

            JsonObject jsonObject = new JsonObject ();
            JsonArray jsonArray = new JsonArray ();
            // 循环结果集列表条数
            for (int i = 0,ii = record.size(); i < ii; i++) {
                jsonObject = new JsonObject ();
                // 循环无数据字段量
                for (int j = 0; j < count; j++) {
                    jsonObject.addProperty(
                            colNames[j].replaceAll("\"",""),
                            record.getValue(i,j) != null ? record.getValue(i,j).toString() : "");
                }
                jsonArray.add(jsonObject);
            }
            return jsonArray;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //将查询数据转换为jsonObject
    public static JsonObject dataChangeJsonObject(Record record) {
        try {
            JsonObject jsonObject = new JsonObject ();
            if (record != null) {
                // 元数据的数量
                int count = record.fieldsRow().size();
                String[] colNames = new String[count];
                String field = "";
                for(int i = 0; i < count; i++){
                    // 字段名称
                    field = record.field(i).toString();
                    if (field.contains(".")) {
                        colNames[i] = field.substring(field.lastIndexOf(".") + 1,field.length());
                    }
                    else {
                        colNames[i] = field;
                    }
                }
                for (int j = 0; j < count; j++) {
                    jsonObject.addProperty(
                            colNames[j].replaceAll("\"",""),
                            record.getValue(j) != null ? record.getValue(j).toString() : "");
                }

                return jsonObject;
            } else  {
                return  jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //根据ip获取城市名
    public static String getCityNameByip(String ip){
        JsonObject jsonObject= HttpUtil.getNameByIp ( ip );
        return getJsonAsString ( jsonObject,"city" );
    }


}
